<template>
    <view>
        <view class="tips color_fff size_12 align_c" :class="{ 'show': ajax.loading }">{{ ajax.loadText
            }}
        </view>
        <view class="box-1" id="list-box">

            <view class="talk-list">
                <view v-for="(item, index) in chatList" :key="index" :id="`msg-${item.id}`">
                    <view class="item flex_col" :class="item.role == 'user' ? 'push' : 'pull'">
                        <image :src="user.avatar" mode="aspectFill" class="pic" v-if="item.role == 'user'"></image>
                        <image src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/%E5%95%8A.jpg"
                            mode="aspectFill" class="pic" v-else></image>
                        <view class="content">
                            <!-- {{ item.content }} -->
                            <towxml :nodes="tomarkdown(item.content)" />
                        </view>

                    </view>
                </view>

            </view>
            <view style="height: 100rpx;"></view>
        </view>
        <view class="box-2" v-show="show">
            <view class="flex_col">
                <view class="flex_grow">
                    <input type="text" class="content" v-model="content" placeholder="请输入聊天内容"
                        placeholder-style="color:#DDD;" :cursor-spacing="6">
                </view>
                <button class="voice" @touchstart="touchStart" @touchend="touchEnd">
                    <image src="https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/voice.png" mode="aspectFill"
                        style="width:50rpx;height:50rpx;"></image>
                </button>


                <button class="send" @tap="Ai">发送</button>
            </view>
        </view>
    </view>
</template>



<script>
import towxml from './wxcomponents/towxml/towxml';
import towxml2 from './wxcomponents/towxml/index';
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager();

export default {
    data() {
        return {
            content: '',
            answer: "",
            chatList: [],
            user: {},
            show: true,
            ajax: {
                rows: 20,	//每页数量
                page: 1,	//页码
                flag: true,	// 请求开关
                loading: false,	// 加载中
                loadText: '正在获取消息'
            },
            loading: false

        }
    },
    onLoad() {
        this.user = uni.getStorageSync('user');
        console.log('this.user', this.user)
        this.initRecord();
    },
    components: {
        towxml
    },
    methods: {

        async getAi() {
            let that = this
            //fk213277-R4qHL4g28YI8KGGQAhcfn0ZeZwOkM5RU
            console.log(this.content, 8888)
            if (this.user.gptKey == null) {
                uni.showToast({
                    icon: 'error',
                    title: 'key未配置!',
                });
                return
            }
            if (!this.content) {
                uni.showToast({
                    title: '请先输入问题!',
                });
                return
            }
            this.chatList.push({ role: "user", content: this.content });
            let answer = '正在思考请稍后...'
            this.chatList.push({ role: "assistant", content: "" });
            let index = 0;
            that.answer = ''
            let interval = setInterval(function () {
                that.chatList[that.chatList.length - 1].content += answer[index];
                index++;
                // 当打印完成时，清除定时器
                if (index >= answer.length) {
                    clearInterval(interval);
                }
            },
                150); // 每隔50毫秒打印一个字符



            var data = {

                messages: this.chatList,
                model: 'gpt-4-1106-preview',
                // presence_penalty: 0,
                stream: false,

                top_p: 1,
                temperature: 0.3,
                presence_penalty: 0.6,
                frequency_penalty: 0
                //session_id: new Date()
            };

            uni.request({
                url: 'https://oa.api2d.net/v1/chat/completions', // 请求地址
                method: 'POST',
                header: {
                    'Authorization': `Bearer ` + that.user.gptKey,
                    'Content-Type': 'application/json'
                },
                data: data,
                responseType: 'stream', // 设置响应类型为流式
                success: (res) => {
                    console.log('res', res)
                    // res.data.choices[0].message.content = towxml2(res.data.choices[0].message.content, 'markdown');
                    that.chatList[that.chatList.length - 1] = res.data.choices[0].message
                    that.$forceUpdate();
                    setTimeout(() => {
                        uni.pageScrollTo({
                            scrollTop: 9999999,    //滚动到页面的目标位置（单位px）
                            duration: 0    //滚动动画的时长，默认300ms，单位 ms
                        });
                        this.content = '';
                    }, 100)

                    console.log('chatList', that.chatList)
                },
                fail: (err) => {
                    reject(err);
                }
            });

        },
        async Ai() {
            this.show = false;
            let that = this
            //fk213277-R4qHL4g28YI8KGGQAhcfn0ZeZwOkM5RU
            console.log(this.content, 8888)
            if (this.user.gptKey == null) {
                uni.showToast({
                    icon: 'error',
                    title: 'key未配置!',
                });
                return
            }
            if (!this.content) {
                uni.showToast({
                    title: '请先输入问题!',
                });
                return
            }
            this.chatList.push({ role: "user", content: this.content });
            let answer = '正在思考请稍后...'
            this.chatList.push({ role: "assistant", content: "" });
            let index = 0;
            that.answer = ''
            let interval = setInterval(function () {
                that.chatList[that.chatList.length - 1].content += answer[index];
                index++;
                // 当打印完成时，清除定时器
                if (index >= answer.length) {
                    clearInterval(interval);
                }
            },
                150); // 每隔50毫秒打印一个字符



            var data = {

                messages: this.chatList,
                model: 'gpt-4-all',
                // presence_penalty: 0,
                stream: false,

                top_p: 1,
                temperature: 0.3,
                presence_penalty: 0.6,
                frequency_penalty: 0
                //session_id: new Date()
            };
            var header = 'Authorization:Bearer ' + that.user.gptKey + ';' + 'Content-Type:application/json';
            uni.request({
                url: 'https://zhangteng.cloud:5001/api/mainControllers/CallApiAsync', // 请求地址
                method: 'POST',
                data: {
                    url: 'https://chatapi.onechat.fun/v1/chat/completions', // 请求地址
                    data: JSON.stringify(data),
                    headers: header,
                    method: 'POST',
                },
                header: {
                    'content-type': 'application/x-www-form-urlencoded' // 根据需要修改请求内容类型
                },
                success: (res) => {
                    console.log('res', res)
                    // res.data.choices[0].message.content = towxml2(res.data.choices[0].message.content, 'markdown');
                    that.chatList[that.chatList.length - 1] = res.data.choices[0].message
                    that.$forceUpdate();
                    setTimeout(() => {
                        uni.pageScrollTo({
                            scrollTop: 9999999,    //滚动到页面的目标位置（单位px）
                            duration: 0    //滚动动画的时长，默认300ms，单位 ms
                        });
                        this.content = '';
                        this.show = true;
                    }, 100)

                    console.log('chatList', that.chatList)
                },
                fail: (err) => {
                    reject(err);
                }
            });

        },

        tomarkdown(content) {
            return towxml2(content, 'markdown');
        },
        touchStart: function () {
            uni.showToast({
                title: '语音识别中。。。',
                icon: "none",
                duration: 60000

            });
            manager.start({
                duration: 60000,
                lang: "zh_CN"
            });
        },
        touchEnd: function () {
            uni.hideToast();
            manager.stop();
        },
        /**  
         * 初始化语音识别回调  
         * 绑定语音播放开始事件  
         */
        initRecord: function () {
            manager.onStart = function (res) {
                this.content = "onStart:" + res.msg + "正在录音"
            };
            //有新的识别内容返回，则会调用此事件  
            manager.onRecognize = (res) => {
                this.content = res.result;
            }

            // 识别结束事件  
            manager.onStop = (res) => {

                this.content = res.result;
            }

            // 识别错误事件  
            manager.onError = (res) => {

                this.content = res.msg;

            }
        },

    }
}
</script>

<style lang="scss">
@import "./global.scss";

page {
    background-color: #F3F3F3;
    font-size: 28rpx;
}

/* 加载数据提示 */
.tips {
    position: fixed;
    left: 0;
    top: var(--window-top);
    width: 100%;
    z-index: 9;
    background-color: rgba(0, 0, 0, 0.15);
    height: 72rpx;
    line-height: 72rpx;
    transform: translateY(-80rpx);
    transition: transform 0.3s ease-in-out 0s;

    &.show {
        transform: translateY(0);
    }
}

.box-1 {
    width: 100%;
    height: auto;
    padding-bottom: 100rpx;
    box-sizing: content-box;

    /* 兼容iPhoneX */
    margin-bottom: 0;
    margin-bottom: constant(safe-area-inset-bottom);
    margin-bottom: env(safe-area-inset-bottom);
}

.box-2 {
    position: fixed;
    left: 0;
    width: 100%;
    bottom: 0;
    height: auto;
    z-index: 2;
    border-top: #e5e5e5 solid 1px;
    box-sizing: content-box;
    background-color: #F3F3F3;

    /* 兼容iPhoneX */
    padding-bottom: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    >view {
        padding: 0 20rpx;
        height: 100rpx;
    }

    .content {
        background-color: #fff;
        height: 64rpx;
        padding: 0 20rpx;
        border-radius: 32rpx;
        font-size: 28rpx;
    }

    .send {
        background-color: #42b983;
        color: #fff;
        height: 64rpx;
        margin-left: 20rpx;
        border-radius: 32rpx;
        padding: 0;
        width: 120rpx;
        line-height: 62rpx;

        &:active {
            background-color: #5fc496;
        }
    }

    .voice {
        background-color: #DCDCDC;
        color: #000;
        height: 64rpx;
        margin-left: 20rpx;
        border-radius: 50%;
        padding: 7rpx 7rpx 7rpx 7rpx;
        width: 64rpx;
        line-height: 62rpx;

        &:active {
            background-color: #BEBEBE;
        }
    }
}

.talk-list {
    padding-bottom: 20rpx;

    /* 消息项，基础类 */
    .item {
        padding: 20rpx 20rpx 0 20rpx;
        align-items: flex-start;
        align-content: flex-start;
        color: #333;

        .pic {
            width: 62rpx;
            height: 62rpx;
            margin-top: 15rpx;
            border-radius: 50%;
            border: #fff solid 1px;
        }

        .content {
            padding: 20rpx;
            border-radius: 4px;
            max-width: 600rpx;
            word-break: break-all;
            line-height: 52rpx;
            position: relative;
        }

        /* 收到的消息 */
        &.pull {
            .content {
                margin-left: 18rpx;
                background-color: #fff;

                &::after {
                    content: '';
                    display: block;
                    width: 0;
                    height: 0;
                    border-top: 16rpx solid transparent;
                    border-bottom: 16rpx solid transparent;
                    border-right: 20rpx solid #fff;
                    position: absolute;
                    top: 30rpx;
                    left: -18rpx;
                }
            }
        }

        /* 发出的消息 */
        &.push {
            /* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
            flex-direction: row-reverse;

            .content {
                margin-right: 18rpx;
                background-color: #a0e959;

                &::after {
                    content: '';
                    display: block;
                    width: 0;
                    height: 0;
                    border-top: 16rpx solid transparent;
                    border-bottom: 16rpx solid transparent;
                    border-left: 20rpx solid #a0e959;
                    position: absolute;
                    top: 30rpx;
                    right: -18rpx;
                }
            }
        }
    }
}
</style>